/*
https://leetcode.cn/problems/length-of-longest-subarray-with-at-most-k-frequency/submissions/562208668/
LC2958. 最多K个重复元素的最长子数组
*/
class Solution {
public:
    int longestSubarray(vector<int>& nums) {
        int len=0,r=0;
        int num=0,zero=0;
        int pos=0;
        int n=nums.size();
        for(;r<nums.size();++r){
            if(nums[r]==1) 
            {
                ++num;
                len=max(len,num);
            }
            else {
                if(!zero){
                ++zero;
                pos=r;
                }
                else {
                    zero=0;
                    num=0;
                    r=pos;
                }
            }
        }
        if(len==n) return nums.size()-1;
        return len;
    }
};